package com.qys.livesMall.shop.controller.app;

import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qys.livesMall.app.user.service.IH2AppUserService;
import com.qys.livesMall.cache.words.annotation.CheckWord;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.ip.IpUtil;
import com.qys.livesMall.finance.model.entity.shop.FinanceShopAccount;
import com.qys.livesMall.finance.service.FinanceShopAccountService;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.framework.view.QysPage;
import com.qys.livesMall.shop.modal.dto.*;
import com.qys.livesMall.shop.modal.dto.shop.AppAddShop;
import com.qys.livesMall.shop.modal.dto.shop.EditShop;
import com.qys.livesMall.shop.modal.dto.shop.EditShopPassword;
import com.qys.livesMall.shop.modal.dto.shop.ShopSearch;
import com.qys.livesMall.shop.modal.dto.shop.contract.EditContract;
import com.qys.livesMall.shop.modal.entity.H2DataPackage;
import com.qys.livesMall.shop.modal.entity.H2ShopBase;
import com.qys.livesMall.shop.modal.entity.SysPacketEffect;
import com.qys.livesMall.shop.modal.vo.*;
import com.qys.livesMall.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * App店铺基础
 *
 * @author makejava
 * @since 2023-05-26 10:28:08
 */
@RestController
@RequestMapping("/app/shop")
@Tag(name = "App-商品", description = "App-商品")
public class AppH2ShopBaseController {
    /**
     * 服务对象
     */
    @Resource
    private H2ShopBaseService h2ShopBaseService;

    @Autowired
    private H2ShopContractService shopContractService;

    @Resource
    private H2DataPackageService dataPackageService;

    @Autowired
    private ShopRecordService shopRecordService;

    @Resource
    private SysShopDataConsumeService shopDataConsumeService;

    @Resource
    private SysPacketEffectService packetEffectService;

    @Autowired
    private IH2AppUserService appUserService;

    @Autowired
    private FinanceShopAccountService financeShopAccountService;



    /**
     * 分页查询
     *
     * @param search 筛选条件
     * @return 查询结果
     */
    @PostMapping("/list")
    public R<QysPage<ShopVO>> queryByPage(@RequestBody ShopSearch search) {
        search.setApp(1);
//        app端只显示正常状态的店铺
        search.setStatus(0);
        return R.ok(this.h2ShopBaseService.list(search));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @Deprecated
    @GetMapping("/{id}")
    public R<H2ShopBase> queryById(@PathVariable("id") Long id) {
        return R.ok(this.h2ShopBaseService.queryById(id));
    }

    /**
     * 通过shopId获取店铺
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/get/{shopId}")
    public R<AppShopVO> queryByShopId(@PathVariable("shopId") Long id) {
        AppShopVO vo=this.h2ShopBaseService.queryByShopId(id);
       if (vo==null){
           return R.ok();
       }
        vo.setInterest(shopRecordService.isInterestShop(id));
        return R.ok(vo);
    }

    /**
     * 获取当前用户店铺
     *
     * @return 单条数据
     */
    @GetMapping
    public R<AppShopVO> get() {
        AppShopVO vo=this.h2ShopBaseService.getByApp();
        if (vo==null){
            return R.ok();
        }
        vo.setInterest(shopRecordService.isInterestShop(vo.getId()));
        return R.ok(vo);
    }

    /**
     * 开店申请
     *
     * @param h2ShopBase 实体
     * @return 新增结果
     */
    @PostMapping
    public R add(@RequestBody AppAddShop h2ShopBase, HttpServletRequest request) {
        String ip = IpUtil.getIpAddr(request);
        return h2ShopBaseService.add(h2ShopBase,ip);
    }

    /**
     * 编辑数据
     *
     * @param shop 实体
     * @return 编辑结果
     */
    @CheckWord
    @PutMapping
    public R edit(@RequestBody EditShop shop) {
        return h2ShopBaseService.update(shop);
    }

    /**
     * 获取店铺合同
     * @param shopId
     * @return
     */
    @GetMapping(value = "/shopContract/{shopId}")
    public R<ShopContractVO> getContract(@PathVariable Long shopId) {
        return R.ok(shopContractService.getByShopId(shopId));
    }

    /**
     * 签订合同
     * @param params
     * @return
     */
    @PostMapping(value = "/signContract")
    public R<?> signContract(@RequestBody @Validated EditContract params) {
        return h2ShopBaseService.signContract(params);
    }

    /**
     * 申请关闭店铺
     * @param shopId
     * @return
     */
    @Operation(summary = "申请关闭店铺")
    @PostMapping(value = "/closeShop/{shopId}")
    public R<CloseShopDto> closeShop(@PathVariable Long shopId) {
        return h2ShopBaseService.closeShop(shopId);
    }

    /**
     * 是否已经设置密码
     * @param
     * @return
     */
    @PostMapping(value = "/password/status")
    public R<?> passwordStatus() {
        return h2ShopBaseService.passwordStatus();
    }


    /**
     * 设置（修改）密码
     * @param password
     * @return
     */
    @Deprecated
    @PostMapping(value = "/password/set")
    public R<?> setPassword(@RequestBody EditShopPassword password) {
        return h2ShopBaseService.setPasswordByApp(password);
    }

    @PostMapping("/buyDataPackage")
    @Operation(summary = "店铺购买流量（下单）")
    public R<String> buyDataPackage(@RequestBody BuyDataPackageDTO dto) {
        return R.ok(dataPackageService.buyDataPackage(dto));
    }

    @PostMapping("/payDataPackage")
    @Operation(summary = "店铺购买流量（付款）")
    public R<?> payDataPackage(@RequestBody PayDataPackageDTO dto) {
        try {
            dataPackageService.payDataPackage(dto);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok();
    }

    @PostMapping("/useDataPackage")
    @Operation(summary = "店铺使用流量包")
    public R<?> useDataPackage(@RequestBody UseDataPackageDTO dto) {
        try {
            shopDataConsumeService.useDataPackage(dto);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok();
    }

    @GetMapping("/storeTrafficSurplus/{shopId}")
    @Operation(summary = "店铺流量包剩余")
    public R<ShopTrafficSurplusVO> storeTrafficSurplus(@PathVariable String shopId){
        ShopTrafficSurplusVO result;
        try {
            result = shopDataConsumeService.storeTrafficSurplus(shopId);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok(result);
    }

    @GetMapping("/dataPacList")
    @Operation(summary = "店铺流量列表")
    public R<List<H2DataPackageVO>> dataPacList() {
        Wrapper<H2DataPackage> wrapper = Wrappers.<H2DataPackage>lambdaQuery().eq(H2DataPackage::getIsDelete, 0);
        List<H2DataPackage> list = dataPackageService.list(wrapper);
        List<H2DataPackageVO> collect = null;
        if (CollectionUtils.isNotEmpty(list)) {
            collect = list.stream().map(e -> {
                H2DataPackageVO packageVO = new H2DataPackageVO();
                BeanUtils.copyProperties(e, packageVO);
                packageVO.setPackagePrice(e.getPackagePrice().toString());
                return packageVO;
            }).collect(Collectors.toList());
        }
        return R.ok(collect);
    }

    @GetMapping("/packetEffectList")
    @Operation(summary = "店铺流量效果列表")
    public R<List<SysPacketEffect>> packetEffectList() {
        return R.ok(packetEffectService.list());
    }

    @PostMapping("/address")
    @Operation(summary = "获取地区列表")
    public R<List<QueryAddressVO>> address(@RequestBody QueryAddressDTO dto){
        List<QueryAddressVO> queryAddress = dataPackageService.queryAddress(dto);
        return R.ok(queryAddress);
    }

    @GetMapping("/allAddress")
    @Operation(summary = "所有获取地区列表")
    public R<List<Tree<Integer>>> allAddress(){
        List<Tree<Integer>> trees = dataPackageService.allAddress();
        return R.ok(trees);
    }

    @PostMapping("/sendMessage/{phoneNumber}")
    @Operation(summary = "发送编辑电话验证短信")
    public R<?> sendMessage(@PathVariable String phoneNumber) {
        boolean sendMessage = h2ShopBaseService.sendMessage(phoneNumber);
        if(!sendMessage){
            return R.fail();
        }
        return R.ok();
    }

    @PostMapping("/sendMail/{mailNumber}")
    @Operation(summary = "发送编辑邮箱验证短信")
    public R<?> sendMail(@PathVariable String mailNumber) {
        h2ShopBaseService.sendMail(mailNumber);
        return R.ok();
    }

    @GetMapping("/getPayableEarnestMoney")
    @Operation(summary = "应缴保证金")
    public R<?> getPayableEarnestMoney() {
        return R.ok( h2ShopBaseService.getPayableEarnestMoney());
    }


    @PostMapping("/pay/earnestMoney")
    @Operation(summary = "缴纳保证金")
    public R<?> payEarnestMoney(@RequestBody EditShopPassword shop) {
        //检查密码
        boolean res=appUserService.checkUserPayPassword(SecurityUtils.getUserId().toString(),shop.getPassword());
        if (!res){
            return R.fail();
        }
        h2ShopBaseService.payEarnestMoney();
        return R.ok();
    }

    @PostMapping("/insufficientBalanceTip")
    @Operation(summary = "余额不足提醒")
    public R<Boolean> insufficientBalanceTip() {


        return R.ok();
    }

}

